package servlet;

import bean.Activity;
import bean.Message;
import bean.PageBean;
import dao.ActivityDao;
import dao.MessageDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author yl
 */
public class ActivityServlet extends HttpServlet {
    private ActivityDao activityDao = new ActivityDao();
    private MessageDao messageDao = new MessageDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String t = req.getParameter("t");
        JsonWrapper result = new JsonWrapper();
        if (t != null) {
            // 依据 t
            try {
                switch (t) {
                    case "requests":
                        List<Object> list;
                        try {
                            list = activityDao.findUnProcessAdvice(null);
                            if (list.size() != 0) {
                                result.setStatus(200);
                                result.setMsg("success");
                            } else {
                                result.setStatus(200);
                                result.setMsg("no record!");
                            }

                            JSONArray jsonArray = new JSONArray();
                            for (Object single : list) {
                                JSONObject jsonObject = JsonWrapper.parseFromObject(single);
                                jsonArray.add(jsonObject);
                            }
                            result.setDataEntry("total", list.size());
                            result.setDataJsonArray("values", jsonArray);
                        } catch (Exception e) {
                            result.setStatus(401);  //查询失败
                            result.setMsg("failed");
                            e.printStackTrace();
                        }
                        break;
                    case "havemsg":
                        try {
                            int count = activityDao.findUnProcessAdviceCount();
                            result.setDataEntry("total", count);
                            if (count != 0) {
                                result.setStatus(200);
                                result.setMsg("success");
                            } else {
                                result.setStatus(200);
                                result.setMsg("No record!");
                            }
                        } catch (Exception e) {
                            result.setStatus(401);  //查询失败
                            result.setMsg("failed");
                            e.printStackTrace();
                        }
                        break;
                    default:
                }
            } catch (Exception e) {
                result.setStatus(401);  //查询失败
                result.setMsg("failed");
                e.printStackTrace();
            }
        } else {
            // 依据 type
            String type = req.getParameter("type");
            if (type != null) {
                String prefix = req.getParameter("prefix");
                String value = req.getParameter("value");
                // 模糊查询
                if (prefix != null) {

                    Activity activity = new Activity();
                    if ("userId".equals(type)) {
                        activity.setUserId(req.getParameter("prefix"));
                    } else if ("title".equals(type)) {
                        activity.setTitle(req.getParameter("prefix"));
                    } else if ("status".equals(type)) {
                        activity.setStatus(req.getParameter("prefix"));
                    } else if ("id".equals(type)) {
                        activity.setActivityId(req.getParameter("prefix"));
                    }
                    List<Object> resultActivity;  //查询返回的用户信息
                    JSONArray jsonArray = new JSONArray();
                    try {
                        resultActivity = activityDao.activityList(null, activity, null, null, null, null, null, null);
                        if (resultActivity.size() != 0) {
                            result.setStatus(200);
                            result.setMsg("success");
                        } else {
                            result.setStatus(200);
                            result.setMsg("No record!");
                        }
                        for (Object single : resultActivity) {
                            JSONObject jsonObject = new JSONObject();
                            switch (type) {
                                case "userId":
                                    jsonObject.put("value", ((Activity) single).getUserId());
                                    break;
                                case "title":
                                    jsonObject.put("value", ((Activity) single).getTitle());
                                    break;
                                case "status":
                                    jsonObject.put("value", ((Activity) single).getStatus());
                                    break;
                                case "id":
                                    jsonObject.put("value", ((Activity) single).getActivityId());
                                    break;
                                default:
                            }
                            jsonArray.add(jsonObject);
                        }

                        result.setDataEntry("total", resultActivity.size());
                        result.setDataJsonArray("values", jsonArray);
                    } catch (Exception e) {
                        result.setStatus(401);  //查询失败
                        result.setMsg("failed");
                        e.printStackTrace();
                    }
                } else if (value != null) {
                    // 精确查询
                    try {
                        Activity activity = new Activity();
                        if ("userId".equals(type)) {
                            activity.setUserId(value);
                        } else if ("title".equals(type)) {
                            activity.setTitle(value);
                        } else if ("status".equals(type)) {
                            activity.setStatus(value);
                        } else if ("id".equals(type)) {
                            activity.setActivityId(value);
                            // activityDao.activityClick(value);
                        }
                        List<Object> resultAdvice;  //查询返回的用户信息
                        try {
                            resultAdvice = activityDao.activityList(null, activity, null, null, null, null, null, null);
                            int total = resultAdvice.size();
                            if (total != 0) {
                                result.setMsg("success");
                            } else {
                                result.setMsg("no record!");
                            }
                            result.setStatus(200);
                            result.setDataEntry("total", total);
                            result.setDataObject("value", total == 0 ? new JSONObject() : resultAdvice.get(0));
                        } catch (Exception e) {
                            result.setStatus(401);  //查询失败
                            result.setMsg("failed");
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        result.setStatus(401);  //查询失败
                        result.setMsg("failed");
                        e.printStackTrace();
                    }
                } else {
                    // 错误
                    result.setStatus(400);
                    result.setMsg("invalid request");
                }
            } else {
                // 分页
                String start = req.getParameter("start");  //当前页
                String pageSize = req.getParameter("pagesize");  //页记录数
                if (start != null && pageSize != null) {
                    int s = 0;
                    int ps = 0;
                    List<Object> resultActivity;  //查询返回的用户信息
                    JSONArray jsonArray = new JSONArray();

                    if (!StringUtil.isEmpty(start)) {
                        s = Integer.parseInt(start);
                    }
                    if (!StringUtil.isEmpty(pageSize)) {
                        ps = Integer.parseInt(pageSize);
                    }
                    PageBean pageBean = new PageBean(s, ps);
                    try {
                        resultActivity = activityDao.activityList(pageBean, new Activity(), null, null, null, null, null, null);
                        if (resultActivity.size() != 0) {
                            result.setStatus(200);
                            result.setMsg("success");
                        } else {
                            result.setStatus(200);
                            result.setMsg("No record!");
                        }

                        for (Object single : resultActivity) {
                            JSONObject jsonObject = JsonWrapper.parseFromObject(single);
                            jsonArray.add(jsonObject);
                        }
                        result.setDataEntry("total", resultActivity.size());
                        result.setDataJsonArray("values", jsonArray);
                    } catch (Exception e) {
                        //查询失败
                        result.setStatus(401);
                        result.setMsg("query failed");
                        e.printStackTrace();
                    }
                } else {
                    try {
                        // total
                        try {
                            int count = activityDao.activityCount(new Activity(), null, null, null, null, null, null);
                            result.setDataEntry("total", count);
                            if (count != 0) {
                                result.setStatus(200);
                                result.setMsg("success");
                            } else {
                                result.setStatus(200);
                                result.setMsg("No record!");
                            }
                        } catch (Exception e) {
                            result.setStatus(401);  //查询失败
                            result.setMsg("failed");
                            e.printStackTrace();
                        }
                    } catch (Exception e) {
                        result.setStatus(500);
                        result.setMsg("failed");
                    }
                }
            }
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * 管理员批准或者拒绝活动 2 批准 3 拒绝
     */
    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject joa = RequestUtil.getJsonFromRequest(req);
        String status;
        Activity activity = new Activity();
        if (joa != null) {
            status = joa.getString("status");
            if ("2".equals(status) || "3".equals(status)) {
                String now1 = DateUtil.nowTime();
                String now2 = DateUtil.parseTime(now1);
                activity.setReplyTime(now2);
            }
            activity.setActivityId(joa.getString("id"));
            activity.setStatus(joa.getString("status"));
            activity.setReplyContent(joa.getString("replyContent"));
        } else {
            ResponseUtil.writeBadRequest(resp);
            return;
        }
        JsonWrapper result = new JsonWrapper();

        try {
            // real modify
            int modifyNum = activityDao.activityModify(activity);
            if (modifyNum == 1) {
                result.setStatus(200);  //修改成功
                result.setMsg("success");
                List<Object> activityList = activityDao.activityList(null, new Activity(activity.getActivityId()), null, null, null, null, null, null);
                JSONObject jsonObject = JsonWrapper.parseFromObject(activityList.get(0));
                result.setDataEntry("total", 1);
                result.setDataJsonObject("values", jsonObject);
                // send message
                if ("2".equals(status)) {
                    sendMessage(jsonObject.getString("userId"), "恭喜，活动【主题：" + jsonObject.getString("title") + ",内容：" + jsonObject.getString("description") + "】已创建成功！请您务必在" + jsonObject.getString("createTime") + "到" + jsonObject.getString("startTime") + "之间将活动筹备完毕，预祝活动圆满成功！");
                } else {
                    sendMessage(jsonObject.getString("userId"), "抱歉，活动【主题：" + jsonObject.getString("title") + ",内容：" + jsonObject.getString("description") + "】创建失败！管理员回复：" + jsonObject.getString("replyContent") + "，请您仔细核对创建活动的必要信息，如仍有问题或疑问请及时于管理员联系，谢谢!");
                }
            } else {
                result.setStatus(400);  //修改失败
                result.setMsg("修改成功的记录：0条");
            }
        } catch (Exception e) {
            result.setStatus(401);  //修改失败
            result.setMsg("failed");
            e.printStackTrace();
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * 删除
     */
    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        JsonWrapper result = new JsonWrapper();
        try {
            int delNum = activityDao.activityDelete(req.getParameter("id"));
            if (delNum == 1) {
                result.setStatus(200);  //删除成功
                result.setMsg("success");
            } else {
                result.setStatus(400);  //删除失败
                result.setMsg("删除成功的记录：0条");
            }
        } catch (Exception e) {
            result.setStatus(404);  //删除失败
            result.setMsg("failed");
            e.printStackTrace();
        }
        ResponseUtil.write(resp, result.get());
    }

    /**
     * 增加
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject json = RequestUtil.getJsonFromRequest(req);
        if (json != null) {
            Activity activity = new Activity();
            activity.setUserId(json.getString("creator"));
            activity.setTitle(json.getString("title"));
            String now1 = DateUtil.nowTime();
            String now2 = DateUtil.parseTime(now1);
            Date time = DateUtil.parse(now2);
            activity.setCreateTime(now2);
            activity.setReplyTime(now2);
            Long startTime = json.getLong("startTime");
            Long endTime = json.getLong("endTime");
            Date time1 = new Date(startTime);
            Date time2 = new Date(endTime);
            activity.setStartTime(DateUtil.getStringDate(time1));
            activity.setEndTime(DateUtil.getStringDate(time2));
            activity.setDescription(json.getString("description"));
            activity.setStatus("2");
            activity.setTempCount("0");
            String maxCount = json.getString("maxUserCount");
            if (maxCount != null) {
                activity.setMaxUserCount(maxCount);
            } else {
                activity.setMaxUserCount("50");
            }
            activity.setClick("0");

            JsonWrapper result = new JsonWrapper();

            try {
                boolean rightTime = time.getTime() <= time1.getTime() && time1.getTime() < time2.getTime();
                if (rightTime) {
                    boolean result1 = activityDao.activityAdd(activity);
                    if (result1) {
                        result.setStatus(200);  //
                        result.setMsg("success");
                        result.setDataEntry("total", 1);
                    } else {
                        result.setStatus(400);  //
                        result.setMsg("数据库更新失败");
                    }
                } else {
                    result.setStatus(400);  //
                    result.setMsg("请确保创建时间<=开始时间<结束时间");
                }
            } catch (Exception e) {
                result.setStatus(401);  //
                result.setMsg("failed");
                e.printStackTrace();
            }
            ResponseUtil.write(resp, result.get());
        } else {
            ResponseUtil.write(resp, JsonWrapper.builder().setStatus(400).setMsg("failed").build());
        }
    }

    private void sendMessage(String rid, String content) throws Exception {
        Message message = new Message();
        message.setSendId("1");
        message.setReceiveId(rid);
        message.setContent(content);
        message.setStatus("0");
        message.setSendTime(DateUtil.nowSymbolTime());
        messageDao.messageAdd(message);
    }
}
